package com.robusta.cityuate.activities;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.robusta.cityuate.R;
import com.robusta.cityuate.base.CityuateFragmentMenuActivity;
import com.robusta.cityuate.base.ViewType.Type;
import com.robusta.cityuate.fragments.OfferingsListFragment;
import com.robusta.cityuate.fragments.OfferingsListFragment.SpotCarrier;
import com.robusta.cityuate.fragments.SpotCommentsFragmemt;
import com.robusta.cityuate.objects.Spot;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.services.ImageDownloader;
import com.robusta.cityuate.utils.ConnectionUtils;
import com.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.slidingmenu.lib.SlidingMenu.OnOpenListener;

public class SpotProfileActivity extends CityuateFragmentMenuActivity implements
		SpotCarrier {

	public static final String FAV_TAG = SpotProfileActivity.class.getName()
			+ "_FAVSPOT";
	public static final String REPORT_TAG = SpotProfileActivity.class.getName()
			+ "_REPORTSPOT";

	private Spot spot;
	private ActionBar mActionBar;
	private ImageView imageView;
	private TextView spotname;
	private TextView address;
	private TextView landmarks;
	private ImageDownloader mImageDownloader;
	private OfferingsListFragment offeringsList;
	private SupportMapFragment mapFragment;
	private GoogleMap mMap;
	private Context mContext = this;

	private CityuateBroadCastReceiver favReceiver = new CityuateBroadCastReceiver() {

		@Override
		public void onSuccess() {
			setSupportProgressBarIndeterminateVisibility(false);
			Toast.makeText(mContext, R.string.spot_favorited,
					Toast.LENGTH_SHORT).show();
			if (spot.getIsFavorite() != null)
				spot.setIsFavorite(!spot.getIsFavorite());
			else
				spot.setIsFavorite(true);
			invalidateOptionsMenu();
			ConnectionUtils.clearConnection(mContext, FAV_TAG);
		}

		@Override
		public void onFailure() {
			setSupportProgressBarIndeterminateVisibility(false);
			Toast.makeText(mContext,
					ConnectionUtils.getExtra(mContext, FAV_TAG),
					Toast.LENGTH_SHORT).show();
			ConnectionUtils.clearConnection(mContext, FAV_TAG);
		}

		@Override
		public void onCancel() {
			setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, FAV_TAG);
		}
	};

	private CityuateBroadCastReceiver reportReceiver = new CityuateBroadCastReceiver() {
		@Override
		public void onSuccess() {
			setSupportProgressBarIndeterminateVisibility(false);
			Toast.makeText(mContext,
					mContext.getResources().getString(R.string.report_succ),
					Toast.LENGTH_SHORT).show();
			ConnectionUtils.clearConnection(mContext, REPORT_TAG);
		}

		@Override
		public void onFailure() {
			setSupportProgressBarIndeterminateVisibility(false);
			Toast.makeText(mContext,
					ConnectionUtils.getExtra(mContext, REPORT_TAG),
					Toast.LENGTH_SHORT).show();
			ConnectionUtils.clearConnection(mContext, REPORT_TAG);
		}

		@Override
		public void onCancel() {
			setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, REPORT_TAG);
		}
	};
	private SpotCommentsFragmemt commentsFragmemt;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		super.onCreate(savedInstanceState);
		mActionBar = getSupportActionBar();

		setContentView(R.layout.spot_profile_view);

		mImageDownloader = new ImageDownloader();

		spot = (Spot) getIntent().getSerializableExtra(Spot.SPOT);
		imageView = (ImageView) findViewById(R.id.spot_image);
		spotname = (TextView) findViewById(R.id.spot_name);
		address = (TextView) findViewById(R.id.spot_address);
		landmarks = (TextView) findViewById(R.id.spot_landmarks);

		offeringsList = (OfferingsListFragment) getSupportFragmentManager()
				.findFragmentById(R.id.offerings_list);

		mapFragment = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map);
		mMap = mapFragment.getMap();

		sideMenu.setOnClosedListener(new OnClosedListener() {

			@Override
			public void onClosed() {
				mapFragment.getView().setVisibility(View.VISIBLE);

			}
		});
		sideMenu.setOnOpenListener(new OnOpenListener() {

			@Override
			public void onOpen() {
				mapFragment.getView().setVisibility(View.GONE);

			}

		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		mContext.registerReceiver(favReceiver, new IntentFilter(FAV_TAG));
		mContext.registerReceiver(reportReceiver, new IntentFilter(REPORT_TAG));

		if (ConnectionUtils.isConnecting(mContext, FAV_TAG)
				|| ConnectionUtils.isConnecting(mContext, REPORT_TAG))
			setSupportProgressBarIndeterminateVisibility(true);

		if (ConnectionUtils.wasConnected(mContext, FAV_TAG))
			// connection was successful
			if (ConnectionUtils.isResultSuccessful(mContext, FAV_TAG))
				favReceiver.onSuccess();
			else
				favReceiver.onFailure();

		if (ConnectionUtils.wasConnected(mContext, REPORT_TAG))
			// connection was successful
			if (ConnectionUtils.isResultSuccessful(mContext, REPORT_TAG))
				reportReceiver.onSuccess();
			else
				reportReceiver.onFailure();

		fillSpotData();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("onActivity result", "req_code " + requestCode);
		switch (requestCode) {
		case OfferingCreateEditActivity.OFFER_CREATEEDIT_CODE:
			if (resultCode == RESULT_OK)
				offeringsList.getOfferings();
			break;

		case SpotCreateEditActivity.SPOT_CREATEEDIT_CODE:
			if (resultCode == RESULT_OK)
				offeringsList.getOfferings();
			break;
		case OfferingPofileActivity.SHOW_OFFER_CODE:
			if (resultCode == RESULT_CANCELED)
				offeringsList.getOfferings();
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public Spot getSpot() {
		return spot;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.spot_profile_option_menu, menu);
		if (ownershipType != null && ownershipType == Type.RENTER) {
			menu.removeItem(R.id.edit);
			menu.removeItem(R.id.new_offering);
			if (spot.getIsFavorite() != null
					&& spot.getIsFavorite().booleanValue())
				menu.removeItem(R.id.favorite);
			else
				menu.removeItem(R.id.unfavorite);

		} else {
			menu.removeItem(R.id.report);
			menu.removeItem(R.id.unfavorite);
			menu.removeItem(R.id.favorite);

		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.edit:

			Intent editSpot = new Intent(this, SpotCreateEditActivity.class);
			editSpot.putExtra(SpotCreateEditActivity.IS_EDIT, true);
			editSpot.putExtra(Spot.SPOT, spot);
			startActivityForResult(editSpot,
					SpotCreateEditActivity.SPOT_CREATEEDIT_CODE);
			return true;

		case R.id.new_offering:
			Intent newOffer = new Intent(this, OfferingCreateEditActivity.class);
			newOffer.putExtra(Spot.SPOT, spot);
			this.startActivityForResult(newOffer,
					OfferingCreateEditActivity.OFFER_CREATEEDIT_CODE);
			return true;

		case R.id.favorite:
			// progressBar.setVisibility(View.VISIBLE);
			setSupportProgressBarIndeterminateVisibility(true);
			spot.toggleFavorite(mContext, true, FAV_TAG);
			return true;

		case R.id.unfavorite:
			// progressBar.setVisibility(View.VISIBLE);
			setSupportProgressBarIndeterminateVisibility(true);
			spot.toggleFavorite(mContext, false, FAV_TAG);
			return true;

		case R.id.report:
			setSupportProgressBarIndeterminateVisibility(true);
			spot.report(mContext, REPORT_TAG);
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void setSpot(Spot spot) {
		this.spot = spot;
		fillSpotData();

	}

	private void fillSpotData() {

		mActionBar.setTitle(spot.getName());

		LatLng loc = new LatLng(spot.getLat(), spot.getLongt());
		mMap.addMarker(new MarkerOptions().position(loc).icon(
				BitmapDescriptorFactory.fromResource(R.drawable.marker)));
		mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 14));

		spotname.setText(spot.getName());
		address.setText(spot.getAddress());
		landmarks.setText(spot.getLandmarks());
		mImageDownloader.download(spot.getImgURL(), imageView);

	}

	public void startNavigation(View v) {
		Intent intent = new Intent(Intent.ACTION_VIEW,
				Uri.parse("google.navigation:q=" + spot.getLat() + ","
						+ spot.getLongt()));
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);

	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(favReceiver);
		unregisterReceiver(reportReceiver);

		if (!ConnectionUtils.isConnecting(mContext, FAV_TAG)) {
			ConnectionUtils.clearConnection(mContext, FAV_TAG);
		}

		if (!ConnectionUtils.isConnecting(mContext, REPORT_TAG)) {
			ConnectionUtils.clearConnection(mContext, REPORT_TAG);
		}

	}

	@Override
	public Type getOwnershipType() {
		return ownershipType;
	}

	public void showComments(View v) {
		FragmentManager fm = getSupportFragmentManager();
		commentsFragmemt = SpotCommentsFragmemt.getInstance(spot);
		commentsFragmemt.show(fm, "Comments");
	}

}
